package com.example.im.ui.fragment

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.R
import com.example.im.callback.OnClickRoomListener
import com.example.im.bean.UserRoom
import com.example.im.common.Constants
import com.example.im.db.DatabaseStorage
import com.example.im.ui.adapter.RoomInviteAdapter
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import kotlinx.android.synthetic.main.fragment_room_invite.*

class RoomInviteFragment : AbstractBaseFragment<BasePresenter<*>>(), View.OnClickListener {


    var adapter: RoomInviteAdapter? = null

    private var mOnClickRoomListener: OnClickRoomListener? = null

    companion object {
        fun newInstance(userRooms: ArrayList<UserRoom>): RoomInviteFragment {
            val bundle = Bundle()
            bundle.putSerializable(Constants.BUNDLE_T0_USER_ROOM_DATA, userRooms)
            val fragment = RoomInviteFragment()
            fragment.arguments = bundle
            return fragment
        }

        fun newInstance(): RoomInviteFragment {
            return RoomInviteFragment()
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mOnClickRoomListener = context as OnClickRoomListener
    }

    override val layoutId: Int
        get() = R.layout.fragment_room_invite

    override fun initView() {

        adapter = RoomInviteAdapter(activity!!, mutableListOf())
        recycler_view.layoutManager = LinearLayoutManager(activity!!)
        recycler_view.adapter = adapter

        tv_room_invite.setOnClickListener(this)

        val friends = DatabaseStorage.getUserRoomStorageByType(1)
            ?:return
        val friendNews = mutableListOf<UserRoom>()
        friends.forEach { f ->
            val isEqual = getOwners().none { o ->
                o.account == f.account
            }
            if (!isEqual) {
                f.sub = -1
            }
            friendNews.add(f)
        }
        adapter!!.addData(friendNews)
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    override fun onClick(v: View?) {
        mOnClickRoomListener!!.onClickInvite(v!!, adapter!!.getSelectedItem())
    }

    private fun getOwners(): MutableList<UserRoom> {
        if (arguments == null)
            return ArrayList()
        val arrayList =
            (arguments!!.getSerializable(Constants.BUNDLE_T0_USER_ROOM_DATA)
                ?: return mutableListOf())
                    as ArrayList<*>
        val owners = mutableListOf<UserRoom>()
        arrayList.forEach {
            owners.add(it as UserRoom)
        }
        return owners
    }
}